package org.gushi.datastruct.a06;

import org.gushi.datastruct.a06.printer.BinaryTreeInfo;

import java.util.Comparator;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * 平衡二叉树的实现
 * <p>
 * BinaryTreeInfo  : 属于二叉树打印工具的实现
 *
 * @param <E>
 */
public class BinarySearchTree<E> implements BinaryTreeInfo {

    private int size;

    private Node<E> root;

    private Comparator<E> comparator;

    public BinarySearchTree() {
    }

    public BinarySearchTree(Comparator<E> comparator) {
        this.comparator = comparator;
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size <= 0;
    }

    public void add(E element) {
        elementNotNullCheck(element);

        //如果是第一个节点
        if (size == 0) {
            root = new Node<>(element, null);
            size++;
            return;
        }
        /**
         * 思路  找到父节点  创建一个新的节点， 然后根据大小决定该节点放在节点左边还是右边
         */

        Node<E> node = root;
        Node<E> parent = root;
        int cmp = 0;
        while (node != null) {

            cmp = compare(element, node.element);
            parent = node;
            if (cmp > 0) {
                node = node.right;
            } else if (cmp < 0) {
                node = node.left;
            } else {
                node.element = element;//覆盖
                return;
            }
        }

        Node<E> nodeNew = new Node<>(element, parent);

        if (cmp > 0) {
            parent.right = nodeNew;
        } else if (cmp < 0) {
            parent.left = nodeNew;
        }
        size++;
    }

    private int compare(E e1, E e2) {
        if (comparator != null) {//如果自定义的比较器为空
            return comparator.compare(e1, e2);
        }
        //使用对象的比较器  如果传入的对象没有实现Comparable接口，则报异常  因为平衡二叉树要求必须具备可比较性
        return ((Comparable<E>) e1).compareTo(e2);
    }

    //前序遍历
    public void preorderTraversal() {
        preorderTraversal(root);
    }

    public void preorderTraversal(Node<E> node) {
        if (node == null) return;
        System.out.println(node.element);
        preorderTraversal(node.left);
        preorderTraversal(node.right);

    }

    //前序遍历-访问者
    public void preorder(Visitor<E> visitor) {
        preorder(root, visitor);
    }

    public void preorder(Node<E> node, Visitor<E> visitor) {
        if (node == null) return;
        if (visitor.visit(node.element)) return;
        preorder(node.left, visitor);
        preorder(node.right, visitor);
    }

    //中序遍历
    public void inorderTraversal() {
        inorderTraversal(root);
    }

    public void inorderTraversal(Node<E> node) {
        if (node == null) return;
        inorderTraversal(node.left);
        System.out.println(node.element);
        inorderTraversal(node.right);
    }

    //中序遍历-访问者
    public void inorder(Visitor<E> visitor) {
        inorder(root, visitor);
    }

    public void inorder(Node<E> node, Visitor<E> visitor) {
        if (node == null) return;
        inorder(node.left, visitor);
        if (visitor.visit(node.element)) return;
        inorder(node.right, visitor);
    }


    //后序遍历
    public void lastOrderTraversal() {
        lastOrderTraversal(root);
    }

    public void lastOrderTraversal(Node<E> node) {
        if (node == null) return;
        lastOrderTraversal(node.left);
        lastOrderTraversal(node.right);
        System.out.println(node.element);

    }

    //中序遍历-访问者
    public void lastOrder(Visitor<E> visitor) {
        lastOrder(root, visitor);
    }

    public void lastOrder(Node<E> node, Visitor<E> visitor) {
        if (node == null) return;
        lastOrder(node.left, visitor);
        lastOrder(node.right, visitor);
        if (visitor.visit(node.element)) return;
    }

    //层序遍历
    public void levelOrderTraversal() {
        levelOrderTraversal(root);
    }

    public void levelOrderTraversal(Node<E> node) {
        Queue<Node<E>> queue = new ArrayBlockingQueue(1000);
        queue.offer(node);
        while (queue.size() > 0) {
            Node<E> nodeTem = queue.poll();
            System.out.println(nodeTem.element);
            if (nodeTem.left != null) {
                queue.offer(nodeTem.left);
            }
            if (nodeTem.right != null) {
                queue.offer(nodeTem.right);
            }
        }
    }

    public void levelOrder(Visitor<E> visitor) {
        Queue<Node<E>> queue = new ArrayBlockingQueue(1000);
        queue.offer(root);
        while (queue.size() > 0) {
            Node<E> nodeTem = queue.poll();
            if (visitor.visit(nodeTem.element)) return;
            if (nodeTem.left != null) {
                queue.offer(nodeTem.left);
            }
            if (nodeTem.right != null) {
                queue.offer(nodeTem.right);
            }
        }
    }


    /**
     * 递归的方式获取树的高度
     *
     * @return
     */
    public int height() {
        return height(root);
    }

    public int height(Node<E> node) {
        if (node == null) return 0;

        //一个节点的作为root计算的高度等于 子节点数+1
        return 1 + Math.max(height(node.left), height(node.right));
    }

    /**
     * 迭代的方式获取树的高度
     * 层次遍历
     *
     * @return
     */
    public int height1() {
        if (root == null) return 0;
        Queue<Node<E>> queue = new ArrayBlockingQueue(1000);
        queue.offer(root);
        int height = 0;
        int levelSize = 1;

        while (queue.size() > 0) {
            Node<E> nodeTem = queue.poll();
            levelSize--;
            if (nodeTem.left != null) {
                queue.offer(nodeTem.left);
            }
            if (nodeTem.right != null) {
                queue.offer(nodeTem.right);
            }

            if (levelSize == 0) {
                height++;
                levelSize = queue.size();
            }

        }

        return height;
    }

    /**
     * 获取前驱节点
     */
    public Node<E> predecessor(Node<E> node) {
        if (node == null) return null;
        Node<E> p = node.left;
        if (p != null) {//等于左子树的最大值的那个节点
            while (p.right != null) {
                p = p.right;
            }
            return p;
        }
        //如果没有左子树，父节点的右节点等于该节点停止，如果找到根节点还没有 代表该节点没有前驱节点
        while (node.parent != null && node == node.parent.left) {
            node = node.parent;
        }
//        if(node.parent==null){
//            return null;
//        }
        return node.parent;
    }


    /**
     * 获取后驱节点
     */
    public Node<E> successor(Node<E> node) {
        if (node == null) return null;
        Node<E> p = node.right;
        if (p != null) {//等于左子树的最大值的那个节点
            while (p.left != null) {
                p = p.left;
            }
            return p;
        }
        while (node.parent != null && node == node.parent.right) {
            node = node.parent;
        }
//        if(node.parent==null){
//            return null;
//        }
        return node.parent;
    }


    public void clear() {
        root = null;
        size = 0;
    }

    public void remove(E element) {
        remove(node(element));
    }

    public void remove(Node<E> node) {
        if (node == null) {
            return;
        }
        /*
         * 删除度为2的节点
         * 逻辑：
         * 1.先用前驱或者是后继节点覆盖原节点的值
         * 2.删除相应的前驱或者后继节点
         * 前驱或者后继 的度只能是1或者0
         */

        if (node.hasTwoChildren()) {
            //删除
            Node<E> s = successor(node);
            node.element = s.element;
            node = s;
        }

        //删除度为1的节点（只有一个孩子的节点），分是左子节点和右子节点的情况
        Node<E> replacement = node.left != null ? node.left : node.right;
        if (replacement != null) {//度为1的节点
            replacement.parent = node.parent;

            if(node.parent==null){//
                root = replacement;
            }else if (node == node.parent.right) {
                node.parent.right = replacement;
            } else {
                node.parent.left = replacement;
            }


        } else {//度为0的节点
            if (node.parent == null) {
                root = null;
            } else {
                if (node == node.parent.right) {
                    node.parent.right = null;
                } else {
                    node.parent.left = null;
                }
            }

        }
        size--;
    }

    private Node<E> node(E element) {
        Node<E> node = root;

        while (node != null) {
            int cpm = compare(element, node.element);
            if (cpm > 0) {
                node = node.right;
            } else if (cpm < 0) {
                node = node.left;
            } else {
                return node;
            }
        }

        return null;


    }

    public boolean contains(E element) {
        return node(element) != null;
    }

    public void elementNotNullCheck(E element) {
        if (element == null) {
            throw new IllegalArgumentException("element must not be null");
        }
    }


    /**
     * BinaryTreeInfo  : 属于二叉树打印工具的实现方法  有4个实现方法
     *
     * @return
     */
    @Override
    public Object root() {
        return root;
    }

    @Override
    public Object left(Object node) {
        return ((Node<E>) node).left;
    }

    @Override
    public Object right(Object node) {
        return ((Node<E>) node).right;
    }

    //告知你要打印的元素
    @Override
    public Object string(Object node) {
        return ((Node<E>) node).element;
    }


    public static interface Visitor<E> {
        boolean visit(E element);
    }


    private static class Node<E> {
        E element;
        Node<E> left;
        Node<E> right;
        Node<E> parent;

        public Node(E element, Node<E> parent) {
            this.element = element;
            this.parent = parent;
        }

        public boolean isLeaf() {
            return left == null && right == null;
        }

        public boolean hasTwoChildren() {
            return left != null && right != null;
        }

    }


}
